const connection = require('../connection/db.config')
const bcrypt = require('bcryptjs');
const saltRounds = 10;
const sql = require('../sql/user')

// 修改密码
async function updatePasswordService(email, password) {
    try {
        const hashPassWord = await bcrypt.hash(password, saltRounds)
        const [res] = await connection.query(sql.updatePasswordSql, [hashPassWord, email])
        return res
    }
    catch (err) {
        throw err
    }
}

// 登录
async function loginService(email) {
    try {
        const [res] = await connection.query(sql.loginSql, [email])
        return res[0]
    }
    catch (err) {
        throw err
    }
}

// 检测数据库表是否存在
async function checkTableService(){
    try {
        const res = await connection.query(sql.checkTableSql)
        return res
    }
    catch (err) {
        throw err
    }
}
// 查询所有用户
async function getUsers() {
    try {
        const res = await connection.query(sql.usersSql)
        return res
    }
    catch (err) {
        throw err
    }
}
// 创建用户
async function ensureUsersService() {
    try {
        const res = await connection.query(sql.ensureUsersSql)
        return res
    }
    catch (err) {
        throw err
    }
}
// 写入注册表
async function registerService(username, email, phone_number, password) {
    // 检查是否所有参数都已定义并且不为空
    if (!username || !email || !password || !phone_number) {
        throw new Error('Username, email, phone_number, and password are required');
    }
    const hashPassWord = await bcrypt.hash(password, saltRounds)
    console.log(hashPassWord,'hashPassWord');
    
    try {
        const res = await connection.query(sql.createUserSql, [username, email, phone_number, hashPassWord])
        return res
    }
    catch (err) {
        throw err
    }
}
// 用户是否存在
async function isUsernameTaken(username) {
    try {
        const [res] = await connection.query(sql.isUsernameTakenSql, [username])
        return res.length > 0
    }
    catch (err) {
        throw err
    }
}
// 邮箱是否存在
async function isEmailTaken(email) {
    try {
        const [res] = await connection.query(sql.isEmailTakenSql, [email])
        return res.length > 0
    }
    catch (err) {
        throw err
    }
}



module.exports = {
    getUsers,
    registerService,
    ensureUsersService,
    checkTableService,
    isUsernameTaken,
    isEmailTaken,
    loginService,
    updatePasswordService
}